<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.search" placeholder="登录名|手机号|姓名" style="width: 200px;" clearable @keyup.enter.native="handleFilter" />
      <el-button v-waves type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="登录名" align="center" prop="userLogin" />
      <el-table-column label="手机号" align="center" prop="userMobile" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="性别" width="100px" align="center" prop="userGender">
        <template slot-scope="{row}">
          <el-tag>{{ row.userGender | genderFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="150px" align="center" prop="userAge" />
      <el-table-column label="账户余额(次数/分钟)" width="200px" align="center">
        <template slot-scope="{row}">
          {{ row.accountBalanceList | reminderTimes }} / {{ row.accountBalanceList | reminderMinutes }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240px" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button type="success" size="mini" @click="showHealthRecordDialog(row)">
            使用
          </el-button>
          <el-button type="success" size="mini" @click="showUsageHistoryDialog(row)">
            记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />

    <el-dialog title="用户账户" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="登录名" prop="userLogin">
          <el-input v-model="temp.userLogin" />
        </el-form-item>
        <el-form-item label="手机号" prop="userMobile">
          <el-input v-model="temp.userMobile" />
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item label="性别" prop="userGender">
          <el-select v-model="temp.userGender" placeholder="请选择">
            <el-option v-for="item in genders" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="userAge">
          <el-input-number v-model="temp.userAge" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData()">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="使用记录" :visible.sync="dialogHistoryVisible" width="500px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px">
        <el-form-item label="使用人姓名" prop="userName">
          {{ temp.userName }}
        </el-form-item>
        <el-form-item label="手机号" prop="userMobile">
          {{ temp.userMobile }}
        </el-form-item>
        <el-form-item label="服务类型" prop="usageType">
          <el-input v-model="temp.usageType" maxlength="30" />
        </el-form-item>
        <el-form-item label="服务次数" prop="usageTimes">
          <el-input-number v-model="temp.usageTimes" @change="onTimesChange" />
        </el-form-item>
        <el-form-item label="服务时长" prop="usageMinutes">
          <el-input-number v-model="temp.usageMinutes" />
        </el-form-item>
        <el-form-item label="服务日期" prop="usageDate">
          <el-date-picker v-model="temp.usageDate" type="datetime" placeholder="选择日期" :picker-options="pickerOptions" />
        </el-form-item>
        <el-form-item label="服务备注">
          <el-input v-model="temp.usageRemark" rows="4" maxlength="1000" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogHistoryVisible = false">取消</el-button>
        <el-button type="primary" @click="addUsageHistory()">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="使用记录" :visible.sync="dialogUsageHistoryDialog" width="70%">
      <el-table :data="history">
        <el-table-column label="使用人姓名" align="center" prop="userName" />
        <el-table-column label="手机号" align="center" prop="userMobile" />
        <el-table-column label="服务类型" align="center" prop="usageType" />
        <el-table-column label="服务消耗">
          <template slot-scope="{row}">
            <span>{{ row.usageTimes }} / {{ row.usageMinutes }}</span>
          </template>
        </el-table-column>
        <el-table-column label="服务日期" align="center" prop="usageDate">
          <template slot-scope="{row}">
            <span>{{ row.usageDate ? new Date(row.usageDate) : '' | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="服务剩余">
          <template slot-scope="{row}">
            <span>{{ row.remainingTimes }} / {{ row.remainingMinutes }}</span>
          </template>
        </el-table-column>
        <el-table-column label="服务备注" align="center" prop="usageRemark" />
      </el-table>
      <pagination v-show="historyTotal>0" :total="historyTotal" :page.sync="historyQuery.current" :limit.sync="historyQuery.size" @pagination="historyList" />
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, updateAccount } from '@/api/user/account'
import { fetchList as fetchUsageHistoryList, createUsageHistory } from '@/api/usage/history'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const genders = [{
  key: 'UNKNOWN',
  label: '保密'
}, {
  key: 'MALE',
  label: '男'
}, {
  key: 'FEMALE',
  label: '女'
}]

const defaultUserAccount = {
  userId: undefined,
  userLogin: undefined,
  userMobile: undefined,
  userName: undefined,
  userGender: undefined,
  userAge: 18
}

export default {
  name: 'MemberManage',
  components: { Pagination },
  directives: { waves },
  filters: {
    genderFilter(gender) {
      return (genders.find(e => e.key === gender) || {}).label || '未知'
    },
    reminderTimes(list) {
      if (!list || list.length === 0) return 0
      const item = list.find(i => i.balanceType === 'REMAINING_TIMES')
      return item ? item.balanceRemaining : 0
    },
    reminderMinutes(list) {
      if (!list || list.length === 0) return 0
      const item = list.find(i => i.balanceType === 'REMAINING_MINUTES')
      return item ? item.balanceRemaining : 0
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        with: 'ACCOUNT_BALANCE',
        current: 1,
        size: 20,
        search: undefined
      },
      genders,
      temp: { ...defaultUserAccount },
      dialogFormVisible: false,
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      dialogHistoryVisible: false,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      dialogUsageHistoryDialog: false,
      historyQuery: {
        current: 1,
        size: 20,
        userId: undefined
      },
      history: [],
      historyTotal: 0
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = { ...defaultUserAccount }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateAccount(tempData).then(() => {
            const index = this.list.findIndex(v => v.userId === this.temp.userId)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    showHealthRecordDialog(row) {
      this.temp = {
        userId: row.userId,
        userName: row.userName,
        userMobile: row.userMobile,
        usageTimes: 1,
        usageMinutes: 20
      }
      this.dialogHistoryVisible = true
    //   this.$router.push({ path: `/member/health-record/${row.id}` })
    },
    onTimesChange() {
      this.temp.usageMinutes = this.temp.usageTimes * 20
    },
    addUsageHistory() {
      const usageHistory = {
        ...this.temp
      }
      createUsageHistory(usageHistory).then(() => {
        this.dialogHistoryVisible = false
        this.getList()
      })
    },
    historyList() {
      this.history = []
      this.historyLoading = true
      fetchUsageHistoryList(this.historyQuery).then(response => {
        this.history = response.data.records
        this.historyTotal = response.data.total
        this.historyLoading = false
      })
    },
    showUsageHistoryDialog(row) {
      this.historyQuery = {
        current: 1,
        size: 20,
        userId: row.userId
      }
      this.historyList()
      this.dialogUsageHistoryDialog = true
    }
  }
}
</script>
